<?php

namespace app\service;

use Qcloud\Cos\Client;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\utils\Arr;

class CosService
{
    /**
     * @var Client
     */
    private static $client = null;

    /**
     * 获取COS客户端实例
     */
    public static function getInstance()
    {
        if (is_null(self::$client)) {
            $logic = new SystemConfigLogic();
            $config = $logic->getGroup('upload_config');
            if (!$config) {
                throw new ApiException('未设置腾讯云配置');
            }

            self::$client = new Client([
                'region' => Arr::getConfigValue($config, 'cos_region'),
                'scheme' => 'https', // 审核时必须为 https
                'credentials' => [
                    'secretId' => Arr::getConfigValue($config, 'cos_secretId'),
                    'secretKey' => Arr::getConfigValue($config, 'cos_secretKey'),
                ],
            ]);
        }
        return self::$client;
    }

    /**
     * 上传文件到COS
     * @param string $filePath 本地文件路径
     * @param string $key 存储的文件名
     * @return string 文件访问URL
     */
    public static function uploadFile($filePath, $key)
    {
        try {
            $logic = new SystemConfigLogic();
            $config = $logic->getGroup('upload_config');
            if (!$config) {
                throw new ApiException('未设置腾讯云配置');
            }

            $bucket = Arr::getConfigValue($config, 'cos_bucket');
            $region = Arr::getConfigValue($config, 'cos_region');
            
            $result = self::getInstance()->putObject([
                'Bucket' => $bucket,
                'Key' => $key,
                'Body' => fopen($filePath, 'rb'),
            ]);

            // 生成访问URL
            $baseUrl = Arr::getConfigValue($config, 'cos_domain') ?: "https://{$bucket}.cos.{$region}.myqcloud.com";
            return rtrim($baseUrl, '/') . '/' . ltrim($key, '/');
        } catch (\Exception $e) {
            throw new ApiException('文件上传失败：' . $e->getMessage());
        }
    }

    /**
     * 审核图片内容
     * @param string $imageUrl 图片URL或本地路径
     * @return array 审核结果
     */
    public static function imageContentCheck($imageUrl)
    {
        try {
            $logic = new SystemConfigLogic();
            $config = $logic->getGroup('upload_config');
            if (!$config) {
                throw new ApiException('未设置腾讯云配置');
            }

            $bucket = Arr::getConfigValue($config, 'cos_bucket');
            $region = Arr::getConfigValue($config, 'cos_region');

            $result = self::getInstance()->detectImage([
                'Bucket' => $bucket,
                'Key' => $imageUrl,
            ]);
            // 解析审核结果
            $label = $result['Label'] ?? 'unknown';
            $score = $result['Score'] ?? 0;
            
            // 根据审核类型判断是否通过
            $hitFlags = [
                $result['PornInfo']['HitFlag'] ?? '0',
                $result['TerrorismInfo']['HitFlag'] ?? '0',
                $result['PoliticsInfo']['HitFlag'] ?? '0',
                $result['AdsInfo']['HitFlag'] ?? '0'
            ];

            // 如果任何一个类型命中，则建议阻止
            $suggestion = in_array('1', $hitFlags) ? 'Block' : 'Pass';
            
            return [
                'suggestion' => $suggestion,    // Block/Pass
                'label' => $label,             // Normal/Porn/Terrorism/Politics/Ads
                'score' => $score,             // 综合得分
                'detail' => [
                    'porn' => $result['PornInfo'] ?? [],
                    'terrorism' => $result['TerrorismInfo'] ?? [],
                    'politics' => $result['PoliticsInfo'] ?? [],
                    'ads' => $result['AdsInfo'] ?? []
                ]
            ];
        } catch (\Exception $e) {
            throw new ApiException('图片审核失败：' . $e->getMessage());
        }
    }

    /**
     * 删除COS中的文件
     * @param string $key 文件路径
     */
    public static function deleteFile($key)
    {
        try {
            $logic = new SystemConfigLogic();
            $config = $logic->getGroup('cos_config');
            if (!$config) {
                throw new ApiException('未设置腾讯云配置');
            }

            $bucket = Arr::getConfigValue($config, 'cos_bucket');
            
            self::getInstance()->deleteObject([
                'Bucket' => $bucket,
                'Key' => $key,
            ]);

            return true;
        } catch (\Exception $e) {
            throw new ApiException('文件删除失败：' . $e->getMessage());
        }
    }
}
